package cn.lwj.webService.util;

import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

public class XmlUtils {
	public final static String TEMP_DIR_PATH = "/zipTempwjj/";
	public final static String TEMP_DIR_PATH_JJ = "/zipTempwjj/jjajxx/";
	
	/**
	 * 写XML文件
	 * @param srcObj
	 * @param targetDirectory
	 * @return
	 * @throws Exception
	 */
	public static String writeXml(Object srcObj, String targetDirectory) throws Exception {
		String filePath = targetDirectory + generateFileName("xml");
		OutputStream out = null;
		XMLEncoder xmlEncoder = null;
		try {
			isDirectory(targetDirectory);
			File file = new File(filePath);
			out = new FileOutputStream(file);
			xmlEncoder = new XMLEncoder(out);
			xmlEncoder.writeObject(srcObj);
		} catch (IOException e) {
			throw e;
		} finally {
			if (xmlEncoder != null) {
				xmlEncoder.flush();
				xmlEncoder.close();
			}
			if (out != null) {
				out.close();
				out = null;
			}
		}
		return filePath;
	}

	/**
	 * 生成随机文件名
	 * 
	 * @param
	 * @return
	 * @throws
	 */
	public static String generateFileName(String suffix) {
		DateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		String formatDate = df.format(new Date());
		int random = new Random().nextInt(10000);
		return formatDate + random + "."+suffix;
	}
	
	/*public static String xmlToZip(Object srcObj,String parentPath){
		try{
			parentPath = parentPath+ XmlUtils.TEMP_DIR_PATH;
			File file = new File(parentPath);
			if(!file.exists()){
				file.mkdirs();
			}
			String filePath = XmlUtils.writeXml(srcObj, parentPath);
			String zipPath = parentPath+ XmlUtils.generateFileName("zip");
			ZipUtils.zipFile(filePath, zipPath);
			delteFile(new File(filePath));
			return zipPath;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}*/
	
	public static void delteFile(File file){
		try {
			if(file.exists()){
				System.gc();
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void isDirectory(String path){
		File f = new File(path);
		if(!f.exists()){
			f.mkdirs();
		}
	}
	
	public static void delDirectory(File file) {
//		System.out.println("file..."+file.getAbsolutePath());
		File[] fileList = file.listFiles();
		if (fileList != null && fileList.length > 0) {
			
			for (File f : fileList) {
//				System.out.println("f..."+f.getAbsolutePath());
				if (f.isDirectory()) {
					delDirectory(f);
				}else{
					f.delete();
				}
			}
			file.delete();
			
		} else {
			file.delete();
		}
	}
	

	
	
	/** 
     * 显示输入流中还剩的字节数 
     *  
     * @param in 
     */  
    private static void showAvailableBytes(InputStream in) {  
        try {  
            System.out.println("当前字节输入流中的字节数为:" + in.available());  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
	/**
	 * 转换xml字符串为map
	 * @author LiuYang
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	public static Map parseXml(String xml) throws Exception{
		if(xml==null||xml.trim().equals("")){
			return new HashMap();
		}
		SAXReader reader = new SAXReader();
		StringReader sr = new StringReader(xml);
		InputSource is = new InputSource(sr);
        Document document = reader.read(is);
        Element root = document.getRootElement();
        Map<String,Object> map = new HashMap<String, Object>();
        Iterator i = root.elements().iterator();
        while(i.hasNext()){
        	Element child = (Element) i.next();
//        	System.out.println("child.elements().size()..."+child.elements().size());
        	if(child.elements().size() == 0){
        		map.put(child.getName(), child.getTextTrim());
        	}else{
        		List<String> lst = new ArrayList<String>();
        		Iterator i2 = child.elements().iterator();
        		while(i2.hasNext()){
        			Element child2 = (Element) i2.next();
        			lst.add(child2.getTextTrim());
        		}
//        		map.put(child.getName().substring(0,child.getName().indexOf("List")), lst);
        		map.put(child.getName(), lst);
        	}
        }
        return map;
	}
	
	/**
	 * 转换map为xml字符串
	 * @author LiuYang
	 * @param map
	 * @return
	 */
	public static String createXml(Map<String,Object> map){
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement(map.getClass().getName());
		for(String key : map.keySet()){
			Element child = root.addElement(key);
			if(map.get(key) instanceof List){
				child.setName(key+"List");
				List lst = (List)map.get(key);
				for(Object str : lst){
					child.addElement(key).setText(str.toString());
				}
			}else
				child.setText(map.get(key).toString());
		}
		return document.asXML();
	}
}
